<?php
namespace app\api\model;

use addons\shopro\model\User;
use app\admin\model\ShoproStoreWaiter;
use addons\shopro\exception\Exception;
use addons\shopro\model\Goods;
use addons\shopro\model\Store;
use app\admin\model\ShoproStoreProject;
use think\helper\Time;
use think\Model;

class SendgoodsServiceModel extends Model
{
    protected $name = 'sendgoods_service';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    // protected $usetimestart = 'usetimestart';
    // protected $usetimeend = 'usetimeend';
    protected $reserveTime = 'reservetime';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    protected $hidden = ['updatetime', 'order_sn', 'goods_id'];

    protected $append = [
        'createtime_text',
        'state_text',
    ];

    public function getImageAttr($var,$data)
    {
        if(!empty($var)){
            return cdnurl($var);
        }
        return '';
    }

    public function getCreatetimeTextAttr($val,$data)
    {
      return date('Y-m-d',$data['createtime']);
    }
    
    public function getStateList()
    {
        return ['0' => __('未使用'), '1' => __('已预约'), '2' => __('已使用')];
    }

    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 发放服务礼遇
     *
     * @param Order $order 订单model
     * @return false
     */
    public static function send($order)
    {
        if (empty($order->item)) {
            log_print(1111111111);
            return false;
        }
        $items = $order->item;
        $goods_ids = array_column($items, 'goods_id');
        if (empty($goods_ids[0])) {
            log_print(2222222222);
            return false;
        }
        $goods_id = $goods_ids[0];
        // 获取订单中是否有颜护系列商品
        $category_id = [15,16]; // 颜护系列脸部和面部id
        $good = Goods::where(['id' => $goods_id])->find();
        if (empty($good)) {
            log_print(33333333333333);
            return false;
        }
        $goodCategoryArr = explode(',', $good['category_ids']);
        if(!in_array(15, $goodCategoryArr) && !in_array(16, $goodCategoryArr)){
            log_print(44444444444);
            return false;
        }

        // 用户等级判断，发放服务礼遇
        $user_id = $order->user_id;
        $userInfo = User::get($user_id);
        $member_level = $userInfo->member_level;

        $max = 0;
        if ($member_level == 5) { // 星耀，每年3次无限期礼遇
            $max = 3;
        } elseif ($member_level == 4) { // 钻石，每年1次礼遇
            $max = 1;
        } else {
            log_print(555555555555555555);
            return false;
        }
        $year = Time::year();
        $servcieCount = self::where('user_id', $user_id)
            ->whereBetween('createtime', $year)
            ->count();
        if ($servcieCount >= $max) {
            log_print(666666);
            return false;
        }
        // 发放礼遇，同一产品更新有效期
        $servcies = self::where('user_id', $user_id)
            ->where('state', 1) // 已预约
            ->whereBetween('createtime', $year)
            ->column('id,usetimeend', 'goods_id');

        if (!empty($servcies[$goods_id])) { // 更新
            $model = self::get($servcies[$goods_id]['id']);
            if ($servcies[$goods_id]['usetimeend'] != 0) {
                // 顺延有效期40天
                $usetimeend = $servcies[$goods_id]['usetimeend'] + Time::daysToSecond(40); 
                $model->usetimeend = $usetimeend;
            } else {
                return false;
            }
        } else { // 新增
            $model = new self();
            $model->user_id = $user_id;
            $model->goods_id = $goods_id;
            $model->order_sn = $order->order_sn ?? '';
            $model->title = $good->title ?? '';
            $model->image = $good->image ?? '';
        }
        // 发放礼遇
        $res = $model->save();
        return $res;
    }


    // 预约
    public static function reserve($params)
    {
        $user = User::info();

        $id = $params['id'] ?? 0;
        $store_id = $params['store_id'] ?? 0;
        $project_id = $params['project_id'] ?? 0;
        $waiter_id = $params['waiter_id'] ?? 0;
        $reservetime = $params['reservetime'] ?? 0;

        $now = time();

        $serviceInfo = (new self)->where('id', $id)->find();
        if (!$serviceInfo) {
            new Exception('礼遇不存在');
        }
        if (!$reservetime) {
            new Exception('请选择预约时间');
        }
        // if ($reservetime < $now) {
        //     new Exception('请选择预约时间');
        // }
        if ($serviceInfo->state != 0) {
            new Exception('请选择需要可以预约的服务礼遇');
        }
        $storeInfo = Store::where(['status' => 1, 'id' => $store_id])->find();
        if (empty($storeInfo)) {
            new Exception('选择预约店铺');
        }
        $projectInfo = ShoproStoreProject::where(['id' => $project_id, 'shopro_store_id' => $store_id])->find();
        if (empty($projectInfo)) {
            new Exception('选择预约项目');
        }
        $waiterInfo = ShoproStoreWaiter::where(['id' => $waiter_id, 'shopro_store_id' => $store_id])->find();
        if (empty($waiterInfo)) {
            new Exception('选择预约技师');
        }
        
        // 会员使用期限计算
        $member_level = $user->member_level;
        if ($member_level < 0 || $member_level > 5) {
            new Exception('不是会员');
        }
        $usetimestart = $now;
        if ($member_level == 5) { // 星耀，没有使用有效期
            $usetimeend = 0;
        } else { // 非星耀有使用有效期
            $usetimeend = $now + Time::daysToSecond(40); // 40天有效期
        }

        // 保存
        $serviceInfo->shopro_store_id = $store_id;
        $serviceInfo->shopro_store_project_id = $project_id;
        $serviceInfo->shopro_store_waiter_id = $waiter_id;
        $serviceInfo->reservetime = $reservetime;
        $serviceInfo->state = 1;
        $serviceInfo->usetimestart = $usetimestart;
        $serviceInfo->usetimeend = $usetimeend;
        $serviceInfo->updatetime = $now;
        $res = $serviceInfo->save();
        if (!$res) {
            new Exception('预约失败');
        }
        return true;
    }

    /**
     * 核销礼券
     *
     * @param int $id
     * @return bool
     */
    public static function use($id)
    {
        $now = time();

        $service = self::get($id);
        if (empty($service)) {
            new Exception('礼遇不存在');
        }
        if ($service->state != 1) {
            new Exception('礼遇未预约或已使用');
        }
        // 已经超过使用期限
        if ($service->usetimeend !=0 && $service->usetimeend < $now) {
            new Exception('服务礼遇已过期');
        }

        $service->state = 2;
        $service->usetime = $now;
        $service->updatetime = $now;
        $res = $service->save();
        if (!$res) {
            new Exception('核销失败');
        }
        return true;
    }
}
